<template>
  <!-- 预览对话框 -->
  <el-dialog
    custom-class="previewIframe"
    :visible.sync="previewVisible"
    fullscreen
    center
    :close-on-click-modal="false"
  >
    <!-- 加载状态 -->
    <div v-if="previewLoading" class="loading-container">
      <!-- <el-progress 
        :percentage="loadProgress" 
        :stroke-width="20"
        :text-inside="true"
        status="success"
      /> -->
      <i class="el-icon-loading" style="font-size: 35px;"></i>
      <p class="loading-text">正在加载文档，请稍候...</p>
    </div>
    
    <!-- PDF 预览容器 -->
    <iframe
      id="pdfIframe"
      ref="pdfIframe"
      :src="iframeSrc"
      frameborder="0"
      width="100%"
      height="100%"
      @load="onIframeLoad"
    ></iframe>
  </el-dialog>
</template>

<script>
export default {
  name: 'PdfPreview',
  data() {
    return {
      previewVisible: false,
      previewLoading: true, // 初始加载状态
      loadProgress: 0, // 加载进度
      iframeSrc: './static/pdfjs/web/viewer.html', // 初始加载空白的PDF查看器
      pdfUrl: '', // PDF文件URL
      blobUrl: null // Blob URL缓存
    }
  },
  methods: {
    // 初始化预览
    init({ downloadUrl }) {
      this.previewVisible = true;
      this.previewLoading = true;
      this.loadProgress = 0;
      
      // 先加载空白查看器
      this.iframeSrc = './static/pdfjs/web/viewer.html';
      
      // 异步加载PDF文件
      this.loadPdfFile(downloadUrl);
    },

    // 加载PDF文件
    async loadPdfFile(url) {
      try {
        // 清除之前的Blob URL
        if (this.blobUrl) {
          URL.revokeObjectURL(this.blobUrl);
          this.blobUrl = null;
        }

        const response = await this.fetchWithProgress(url);
        this.blobUrl = URL.createObjectURL(response);
        
        // 更新iframe URL带上PDF参数
        this.iframeSrc = `./static/pdfjs/web/viewer.html?file=${encodeURIComponent(this.blobUrl)}`;
        
      } catch (error) {
        console.error('PDF加载失败:', error);
        this.$message.error('文档加载失败，请重试');
        this.previewVisible = false;
      }
    },

    // 带进度条的fetch
    async fetchWithProgress(url) {
      const response = await fetch(url, {
        headers: {
          'token': localStorage.getItem('token')
        }
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const contentLength = response.headers.get('content-length');
      const total = parseInt(contentLength || '0', 10);
      let loaded = 0;
      
      const reader = response.body.getReader();
      const chunks = [];
      
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        chunks.push(value);
        loaded += value.length;
        
        // 更新进度
        if (total > 0) {
          this.loadProgress = Math.round((loaded / total) * 100);
        } else {
          // 如果没有content-length，使用简单递增
          this.loadProgress = Math.min(this.loadProgress + 5, 95);
        }
      }
      
      // 合并所有chunks
      const blob = new Blob(chunks);
      this.loadProgress = 100;
      return blob;
    },

    // iframe加载完成回调
    onIframeLoad() {
      // 确保PDF查看器已完全加载
      if (this.blobUrl) {
        setTimeout(() => {
          this.previewLoading = false;
        }, 500); // 添加一点延迟确保查看器稳定
      }
    },

    // 关闭对话框时清理
    handleClose() {
      if (this.blobUrl) {
        URL.revokeObjectURL(this.blobUrl);
        this.blobUrl = null;
      }
      this.previewVisible = false;
    }
  },
  beforeDestroy() {
    // 组件销毁时清理
    if (this.blobUrl) {
      URL.revokeObjectURL(this.blobUrl);
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .previewIframe {
  .el-dialog__body {
    height: calc(100% - 30px);
    position: relative;
  }
}

.loading-container {
  position: absolute;
  top: 10px;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(255, 255, 255, 0.9);
  z-index: 1000;
  
  .el-progress {
    width: 80%;
    max-width: 500px;
    margin-bottom: 20px;
  }
  
  .loading-text {
    font-size: 16px;
    color: #666;
  }
}

#iframe {
  transition: opacity 0.3s;
  
  &[loading] {
    opacity: 0.3;
  }
}
</style>